package qsh.laputa.controller;


import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import qsh.laputa.entity.Account;
import qsh.laputa.entity.Role;
import qsh.laputa.service.AccountService;
import qsh.laputa.service.RoleService;
import qsh.laputa.util.MyQuery;
import qsh.laputa.util.QueryUtil;
import qsh.laputa.util.ResultUtil;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 账号表 前端控制器
 * </p>
 *
 * @author Qsh
 * @since 2021-02-22
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private RoleService roleService;

    /**
     * 进入列表页
     *
     * @return
     */
    @GetMapping("toList")
    public String toList() {
        return "account/accountList";
    }

    /**
     * 查询
     *
     * @return
     */
    @ResponseBody
    @GetMapping("list")
    public R<Map<String, Object>> list(@RequestParam Map<String, String> params) {
        MyQuery<Account> myQuery = QueryUtil.buildMyQuery(params);

        IPage<Account> myPage = accountService.accountPage(myQuery.getPage(), myQuery.getWrapper()
                .eq("a.deleted", 0).eq("r.deleted", 0)
                .orderByDesc("a.account_id"));

        return ResultUtil.buildPageR(myPage);
    }

    /**
     * 进入新增页
     *
     * @return
     */
    @GetMapping("toAdd")
    public String toAdd(Model model) {
        List<Role> roles = roleService.list(Wrappers.<Role>lambdaQuery().orderByAsc(Role::getRoleId));
        model.addAttribute("roles", roles);
        return "account/accountAdd";
    }

    /**
     * 新增账户
     *
     * @param account
     * @return
     */
    @ResponseBody
    @PostMapping("add")
    public R<Object> add(@RequestBody Account account) {
        setPasswordAndSalt(account);
        return ResultUtil.buildR(accountService.save(account));
    }

    /**
     * 设置加密密码和加密盐
     *
     * @param account
     */
    private void setPasswordAndSalt(Account account) {
        String password = account.getPassword();
        //使用UUID作为加密盐
        String salt = UUID.fastUUID().toString().replaceAll("-", "");
        MD5 md5 = new MD5(salt.getBytes());
        //使用加密盐对密码进行加密
        String digestHex = md5.digestHex(password);
        account.setPassword(digestHex);
        account.setSalt(salt);
    }

    /**
     * 进入修改页
     *
     * @return
     */
    @GetMapping("toUpdate/{id}")
    public String toUpdate(@PathVariable Long id, Model model) {
        Account account = accountService.getById(id);
        model.addAttribute("account", account);
        List<Role> roles = roleService.list(Wrappers.<Role>lambdaQuery().orderByAsc(Role::getRoleId));
        model.addAttribute("roles", roles);
        return "account/accountUpdate";
    }

    /**
     * 修改账户
     *
     * @param account
     * @return
     */
    @ResponseBody
    @PutMapping("update")
    public R<Object> update(@RequestBody Account account) {
        if (StringUtils.isNotBlank(account.getPassword())) {
            setPasswordAndSalt(account);
        } else {
            account.setPassword(null);  //忽略密码
        }
        return ResultUtil.buildR(accountService.updateById(account));
    }

    /**
     * 删除账户
     *
     * @return
     */
    @ResponseBody
    @DeleteMapping("toDelete/{id}")
    public R<Object> toDelete(@PathVariable Long id, HttpSession session) {
        Account account = (Account) session.getAttribute("account");
        if (account.getAccountId().equals(id)) {
            return R.failed("不能删除当前账户");
        }
        Account delAccount = new Account();
        delAccount.setAccountId(id);
        return ResultUtil.buildR(accountService.removeByIdWithFill(delAccount));
    }

    /**
     * 进入详情页
     *
     * @return
     */
    @GetMapping("toDetail/{id}")
    public String toDetail(@PathVariable Long id, Model model) {
        Account account = accountService.getAccountById(id);
        model.addAttribute("account", account);
        return "account/accountDetail";
    }

    /**
     * 用户名重名验证(新增/修改)
     *
     * @return
     */
    @ResponseBody
    @GetMapping({"check/{username}", "check/{username}/{accountId}"})
    public R<Object> checkUsername(@PathVariable String username,
                                   @PathVariable(required = false) Long accountId) {
        Integer count = accountService.lambdaQuery()
                .eq(Account::getUsername, username)
                .ne(accountId != null, Account::getAccountId, accountId)
                .count();
        return R.ok(count);
    }

}
